<?php
class Ccbpay
{
    private $antiPhishUrl = "https://ibsbjstar.ccb.com.cn/app/ccbMain";//防钓鱼地址
    private $clientIp = '';
    private $remark1 = "";//备注1
    private $remark2 = "";//备注2
    private $message = '';

    /**
     * 调用建行接口支付
     */
    public function callCcbPay($ccbParameter)
    {
        header("Content-type:text/html;charset=utf-8");
        require_once ('ccb_config.php');
        //生成签名按下列顺序生成 不可改变数组顺序
        $parameter = array(
            'MERCHANTID' => $ccb_config['MERCHANTID'],
            'POSID'      => $ccb_config['POSID'],
            'BRANCHID'   => $ccb_config['BRANCHID'],
            'ORDERID'    => $ccbParameter['orderId'], //订单号
            'PAYMENT'    => $ccbParameter['payment'], //支付金额
            'CURCODE'    => $ccb_config['CURCODE'],
            'TXCODE'     => $ccb_config['TXCODE'],
            'REMARK1'    => $ccbParameter['remark1'], //备注1
            'REMARK2'    => $ccbParameter['remark2'], //备注2
            'TYPE'       => $ccb_config['TYPE'],
            'PUB'        => substr($ccb_config['PUB'], -30),
            'GATEWAY'    => $ccb_config['GATEWAY'],
            'CLIENTIP'   => $this->clientIp,
            'REGINFO'    => $this->escape($ccbParameter['regInfo']), // 网站客户注册信息，中文需使用escape编码
            'PROINFO'    => $this->escape($ccbParameter['proInfo']), // 顾客购买的产品的信息，中文需使用escape编码
            'REFERER'    => $ccb_config['REFERER']
            );
        $sHtml = $this->buildRequestForm($parameter);
        echo $sHtml;
    }

    /**
     * 实现js escape方法  中文需使用escape编码
     * @return [type]      [description]
     */
    public function escape($str)
    {
        if ($str) {
            $sublen = strlen($str);
            $retrunString="";
            for ($i=0;$i<$sublen;$i++) {
                if(ord($str[$i])>=127) {
                    $tmpString = strtoupper(bin2hex(mb_convert_encoding(substr($str, $i, 3), "ucs-2", "UTF-8")));
                    $retrunString.="%u".$tmpString;
                    $i += 2;
                } else  {
                    $retrunString .= $str[$i];
                }
            }
            return $retrunString;
        } else {
            return '';
        }
    }

    /**
     * 生成要请求给支付宝的参数数组
     * @param $para_temp 请求前的参数数组
     * @return 要请求的参数数组
     */
    private function buildRequestPara($para) {
        //生成签名结果 签名结果与签名方式加入请求提交参数组中
        $para['MAC'] = $this->buildRequestMymac($para);

        //仅作为源串参加MD5摘要，不作为参数传递
        unset($para['PUB']);
        return $para;
    }

    private function buildRequestMymac($para)
    {
        $mac = '';
        foreach ($para as $key => $value) {
            $mac .= $key. '='. $value. '&';
        }
        return md5(rtrim($mac, '&'));
    }

    /**
     * 建立请求，以表单HTML形式构造（默认）
     * @param $para_temp 请求参数数组
     * @return 提交表单HTML文本
     */
    private function buildRequestForm($tmp_para) {
        //待请求参数数组
        $params = $this->buildRequestPara($tmp_para);
        $sHtml = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $sHtml .= "<form id='ccbsubmit' name='ccbsubmit' action='". $this->antiPhishUrl."' method='GET' >";
        while (list ($key, $val) = each ($params)) {
            $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
        }

        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml."<input type='submit' value='确认支付'></form>";
        
        $sHtml = $sHtml."<script>document.forms['ccbsubmit'].submit();</script>";
        
        return $sHtml;
    }

    /**
     * 建行同步处理方法
     * @return boolean
     */
    public function responseCcbReturn()
    {
        $param = $_GET;
        require_once("ccb_config.php");
        require_once("ccb_notify.php");
        $ccbNotify = new CcbNotify($ccb_config);

        if ($ccbNotify->verifyNotify($param)) {
            return TRUE;
        } else {
            $this->message = $ccbNotify->getErrorMessages();
            return FALSE;
        }
    }

     /**
     * 建行异步处理方法
     * @return boolean
     */
    public function responseCcbNotify()
    {
        $param = $_POST;
        if (empty($param['ACC_TYPE'])) { //仅服务器通知中有此字段,返回且参与验签
            $this->message = '账户类型错误';
            return FALSE;
        }
        require_once("ccb_config.php");
        require_once("ccb_notify.php");
        $ccbNotify = new CcbNotify($ccb_config);

        if ($ccbNotify->verifyNotify($param)) {
            return TRUE;
        } else {
            $this->message = $ccbNotify->getErrorMessages();
            return FALSE;
        }
    }

    public function getMessage()
    {
        return $this->message;
    }
}